package com.mq.consumer.test;

import com.mq.common.MqConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2019/8/16
 */
public class Consumer2 {

    public static void main(String[] args) {

        try {
            Connection connection = MqConnectionUtils.getConnection();

            Channel channel = connection.createChannel();

            channel.exchangeDeclare("direct-exchange", BuiltinExchangeType.DIRECT);
            channel.queueDeclare("direct-queue", false, false, false, null);
            channel.queueBind("direct-queue", "direct-exchange", "direct-routingKey", null);

            // 1、订阅队列的时候就将auto_ack参数设置为true
            // 2、通过basic.ack显示确认
            channel.basicConsume("direct-queue", true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String key = envelope.getRoutingKey();
                    String message = new String(body);
                    long deliveryTag = envelope.getDeliveryTag();
                    System.out.println("routingKey = " + key + " ; message = " + message + " ; deliveryTag = " + deliveryTag);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
